<?php
namespace Admin\Controller;

use Utuo\BackgroundController;

class ThemeTplController extends BackgroundController {
	
	private $type = array(
			'page' => '单页模板',
			'list' => '列表模板',
			'show' => '详情展示模板',
			'cate' => '栏目展示模板',
	);
	
	private $themeId = 0;
	
	public function _initialize() {
		$this->themeId = I('theme_id', 0, 'intval');
		$this->setControllerTitle("模板管理");
		$this->setActionTitle(array(
			'index' => '模板列表',
			'add' => '添加模板',
			'recycle' => '回收站',
			'modify' => '模板修改',
		), '', 'theme_id='.$this->themeId);
		$this->setActionNav('index,add,recycle');
		$this->assign("theme_id", $this->themeId);
	}
	
	public function indexAction() {
		$this->getLists(0);
	}
	
	// 回收站
	public function recycleAction() {
		$this->getLists(1);
	}
	
	public function getLists( $is_deleted = 0 ) {
		$themeId = $this->themeId;
		$p = I("p", 1, 'intval');
		$condition = array(
			"a.is_deleted" => $is_deleted
		);
		$m = M("ThemeTpl a");
		$themeId and $m->join("__THEME_TPL_AUTH__ b on find_in_set($themeId, b.theme) and a.id=b.tpl_id"); // 列出当前主题下的直属模板(无默认主题模板)
		$n = clone $m;
		$themeTplLists = $m->where($condition)->field("a.*")->order("a.id")->limit($this->getPageSize())->page($this->getPage())->select();
		$count =  $n->count();
		$this->assign("themeTplLists", $themeTplLists);
		$this->showPage($count, $this->getPageSize());
		$this->display();
	}
	
	public function addAction() {
		$themeTpl["themeTplAuth"] = array( 'theme' => $this->themeId );
		$themeTpl["typeOptions"] = $this->getOption($this->type, "", "==请选择模板类型==");
		$this->assign("themeTpl", $themeTpl);
		$this->display('save');
	}
	
	public function modifyAction() {
		$id = I('id', 0, "intval");
		$themeTpl = $this->getOneById("ThemeTpl");
		$themeTpl["themeTplAuth"] = M("ThemeTplAuth")->where(array('tpl_id'=>$id))->find();
		$themeTpl["typeOptions"] = $this->getOption($this->type, $themeTpl['type'], "==请选择模板类型==");
		$this->assign("themeTpl", $themeTpl);
		$this->display('save');
	}
	
	public function saveAction() {
		$this->submitPost("ThemeTpl");
	}
	
	// 移除模块
	public function removePostAction() {
		$this->ajaxRemove();
	}
	
	// 恢复模块
	public function restorePostAction() {
		$this->ajaxRestore();
	}
	
	// 删除模块
	public function deletePostAction() {
		$this->ajaxDelete();
	}
	
	// 状态更新
	public function setStatusPostAction() {
		$id = I("id", 0, "intval");
		$status = I("status", 0, "intval");
		$module = M("ThemeTpl");
		if ($module->where("id={$id}")->setField("status", 1 - $status)) {
			$this->ajaxSuccess();
		} else {
			$this->ajaxError($module->getError());
		}
	}
	
}